package cc.magicjson.synthesis.decorator;



import cc.magicjson.synthesis.model.Order;
import cc.magicjson.synthesis.model.User;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 积分折扣装饰器，为订单添加积分折扣信息
 */
public class PointsDiscountDecorator extends OrderDiscountDecorator {
    private final int pointsPerYuan; // 积分兑换比例：多少积分兑换1元
    private int pointsUsed; // 使用的积分数量
    private BigDecimal discountAmount; // 折扣金额

    public PointsDiscountDecorator(Order order, int pointsPerYuan) {
        super(order);
        this.pointsPerYuan = pointsPerYuan;
        this.pointsUsed = 0;
        this.discountAmount = BigDecimal.ZERO;
    }

    @Override
    public Order applyDiscount() {
        if (!order.isUsePoints()) {
            return order; // 不使用积分折扣
        }

        User user = order.getUser();
        int availablePoints = user.getPoints();

        if (availablePoints <= 0) {
            return order; // 没有可用积分
        }

        // 计算积分可抵扣的最大金额
        BigDecimal maxDiscountAmount = BigDecimal.valueOf(availablePoints)
                .divide(BigDecimal.valueOf(pointsPerYuan), 2, RoundingMode.HALF_UP);

        // 实际抵扣金额不能超过订单金额
        discountAmount = maxDiscountAmount.min(order.getFinalAmount());

        // 计算实际使用的积分
        pointsUsed = discountAmount.multiply(BigDecimal.valueOf(pointsPerYuan))
                .setScale(0, RoundingMode.DOWN).intValue();

        // 重新计算精确的折扣金额
        discountAmount = BigDecimal.valueOf(pointsUsed)
                .divide(BigDecimal.valueOf(pointsPerYuan), 2, RoundingMode.HALF_UP);

        // 更新订单金额
        BigDecimal newFinalAmount = order.getFinalAmount().subtract(discountAmount);
        order.setFinalAmount(newFinalAmount);

        // 更新订单总折扣金额
        BigDecimal newDiscountAmount = order.getDiscountAmount().add(discountAmount);
        order.setDiscountAmount(newDiscountAmount);

        return order;
    }

    @Override
    public String getDiscountDescription() {
        if (pointsUsed > 0) {
            return "使用" + pointsUsed + "积分抵扣" + discountAmount + "元";
        }
        return "未使用积分折扣";
    }

    @Override
    public BigDecimal getDiscountAmount() {
        return discountAmount;
    }

    public int getPointsUsed() {
        return pointsUsed;
    }
}
